<template>
  <input
    type="text"
    class="hminput"
    @input="sendData"
    :class="{ success: isok, error: !isok, default: length == 0 }"
    @blur="showErrorMsg"
  />
</template>

<script>
export default {
  props: {
    reg: {
      type: RegExp,
    },
    msg: {
      type: String,
      default: "数据错误",
    },
  },
  data() {
    return {
      isok: true,
      length: 0,
    };
  },
  methods: {
    sendData(e) {
      this.length = e.target.value.length;
      let v = e.target.value;
      if (this.reg) {
        if (this.reg.test(v)) {
          this.isok = true;
        } else {
          this.isok = false;
        }
      }
      //通过这句话就可以将父级v-model绑定的数值进行双向绑定
      this.$emit("input", e.target.value);
    },
    showErrorMsg(e) {
      let v = e.target.value;
      if (this.reg) {
        if (!this.reg.test(v)) {
          this.$toast.fail(this.msg);
        } else {
        }
      }
    },
  },
};
</script>

<style lang='less' scoped>
.hminput {
  width: 318/360 * 100vw;
  height: 60px;
  position: relative;
  outline: none;
  border: none;
  border-bottom: 3px solid #ccc;
  font-size: 20px;
  line-height: 60px;
}
.success {
  border-bottom-color: green;
}
.error {
  border-bottom-color: red;
}
.default {
  border-bottom-color: #ccc;
}
</style>